from fastapi import APIRouter, Depends, UploadFile, Form, File, BackgroundTasks, Query, Path

from utils import utils
from common.common_response import CommonRes, Token
from bean import UserInfo
from utils import auth
from typing import Union
from client import CosClient
import service
from service import DataPoolService, DataTagService

router = APIRouter(
    prefix="/pool",
    tags=["pool"],
    dependencies=[],
    responses={404: {"description": "Not found"}},
)


@router.post("/upload", description="upload", response_model=CommonRes)
async def upload(tag: Union[str, None] = Form(max_length=20),
                 file: UploadFile = File(),
                 current_user: UserInfo = Depends(auth.get_user), back_task: BackgroundTasks = BackgroundTasks()):
    # back_task.add_task()

    if tag is None or len(tag) == 0:
        tag = utils.get_default_tag()

    tag_uid = await DataTagService.get_tag_uid(current_user, tag)

    async def upload_file(user_id, tenant_id, e_id):
        dat = DataPoolService(user_id, tenant_id, e_id)
        await dat.upload_file(tag_uid, file)

    back_task.add_task(upload_file, current_user.user_id, current_user.tenant_id, current_user.e_id)

    return CommonRes(code=0, message="success", data={
        "url": "hhh"
    })


@router.get("/list", description="list pool", response_model=CommonRes)
async def list_pool(name: Union[str, None] = None,
                    mobile: Union[str, None] = None,
                    email: Union[str, None] = None,
                    page_num: int = Query(default=1),
                    page_size: int = Query(default=20),
                    current_user: UserInfo = Depends(auth.get_user)):
    # back_task.add_task()
    dat = await DataPoolService.list_data()

    return CommonRes(code=0, message="success", data=dat)


@router.get("/tag/{tag_id}/list", description="list pool", response_model=CommonRes)
async def list_tag_pool(*, tag_id: str = Path(title="tag id"),
                        name: Union[str, None] = None,
                        mobile: Union[str, None] = None,
                        email: Union[str, None] = None,
                        page_num: int = Query(default=1),
                        page_size: int = Query(default=20),
                        current_user: UserInfo = Depends(auth.get_user)):
    # back_task.add_task()

    return CommonRes(code=0, message="success", data={
        "url": "hhh"
    })
